package de.sendorian.app.forumArchive.repository;

import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Component;

import de.sendorian.app.forumArchive.domain.File;
import de.sendorian.app.forumArchive.domain.Post;


@Component("fileRepository")
public class FileRepositoryImpl extends RepositoryBase<File> implements FileRepository {

    public FileRepositoryImpl() {
        super(File.class);
    }


    /* (non-Javadoc)
     * @see de.sendorian.app.forumArchive.repository.IFileRepository#findPostByFile(de.sendorian.app.forumArchive.domain.File)
     */
    public Post findPostByFile(File file) {
        String jpql = "select p from Post p,  IN(p.images) i, IN(p.archives) a where i.id = :fileId or a.id = :fileId";
        try {
            return (Post) getEntityManager().createQuery(jpql).setParameter("fileId", file.getId()).getSingleResult();
        } catch (EmptyResultDataAccessException e) {
            //logger.debug("No Topic found for file " + file);
        }
        return null;
    }
    
    /* (non-Javadoc)
     * @see de.sendorian.app.forumArchive.repository.IFileRepository#findByUrl(java.lang.String)
     */
    public File findByUrl(String url) {
        List<File> list = search("url", url);
        return list.isEmpty() ? null : list.get(0);
    }

}
